/*
 * gpio.c
 *
 * Created: 23.05.2013 21:45:01
 *  Author: Vadim Volokitin
 */ 

/* 0 is for burned pin board, normal state is 1 */
#define PORTD2_INT18 1
#include "gpio.h"

/* Default state PB0 is high because the pull-up */
volatile uint8_t portb_state = 0xFF;     

#if PORTD2_INT18
/* Default state PD2 is high because the pull-up */
volatile uint8_t portd_state = 0xFF;

#else
/* Default state PC1 is high because the pull-up */
volatile uint8_t portc_state = 0xFF;

#endif

void gpio_interrupt_init(void)
{
    /* in,PD1. */
    /* Used for UART Tx
	 * DDRD &=~ 0b00000010;
	 */
    /* in,PD2. PCINT18. */
#if PORTD2_INT18    
    DDRD &= ~(1 << DDD2);
	/* Turn ON the Pull-Up onPD2. */
	PORTD |= (1 << PORTD2);  
#else
    /* in,PC1. PCINT9. */
    DDRC &= ~(1 << DDC1);
    /* Turn ON the Pull-Up onPC1. */
    PORTC |= (1 << PORTC1);
#endif


    /* in,PB0. PCINT0. */
    DDRB &= ~(1 << DDB0);
    /* Turn ON the Pull-Up onPB0. */
    PORTB |= (1 << PORTB0);

    PCICR |= (1 << PCIE0);     // set PCIE0 to enable PCMSK0 scan for PCINT0
#if PORTD2_INT18     
    PCICR |= (1 << PCIE2);     // set PCIE2 to enable PCMSK2 scan for PCINT18
#else
	PCICR |= (1 << PCIE1);     // set PCIE1 to enable PCMSK1 scan for PCINT9
#endif
      
    PCMSK0 |= (1 << PCINT0);   // set PCINT0 (pin PB0)to trigger an interrupt on state change
#if PORTD2_INT18 
    PCMSK2 |= (1 << PCINT18);  // set PCINT18(pin PD2) to trigger an interrupt on state change
#else
    PCMSK1 |= (1 << PCINT9);  // set PCINT18(pin PD2) to trigger an interrupt on state change
#endif
	sei();                    // turn on interrupts
	
}


#if PORTD2_INT18 

ISR (PCINT2_vect)
{
    uint8_t current_bit;
    led_set(LED_RED);
    current_bit = PIND ^ portd_state;
    portd_state = PIND;
    if(current_bit & (1 << PD2))
    {
		position++;
    }
    led_clear(LED_RED);
}

#else

ISR (PCINT1_vect)
{
    uint8_t current_bit;
    led_set(LED_RED);
    current_bit = PINC ^ portc_state;
    portc_state = PINC;
    if(current_bit & (1 << PC1))
    {
        position++;
    }
    led_clear(LED_RED);
}

#endif

ISR (PCINT0_vect)
{
	uint8_t current_bit;

	current_bit = PINB ^ portb_state;
	portb_state = PINB;

	led_set(LED_GRN);
	if(current_bit & (1 << PB0))
	{
		position--;
	}
	led_clear(LED_GRN);
}